package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"heightFive/Day_exam/day3/userRpc/global"
	"heightFive/Day_exam/day3/userRpc/models"
	"heightFive/Day_exam/day3/userRpc/vender/consul"
)

func init() {
	InitConfig()
	InitalizeLoggeer()
	MysqlInit()
	InitConsul()
}

func InitConfig() {

	v := viper.New()
	v.SetConfigFile("./nacos.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	NacosConfig := global.NacosConfig{}
	//读取的时候层级关系对应
	if err := v.Unmarshal(&NacosConfig); err != nil {
		panic(err)
	}
	global.NacosServer = &NacosConfig

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosServer.Host,
			Port:   global.NacosServer.Port,
		},
	}

	// 创建动态配置客户端
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosServer.DataId,
		Group:  global.NacosServer.Group})
	if err != nil {
		panic(err)
	}

	ServerConfig := global.ServerConfig{}
	json.Unmarshal([]byte(content), &ServerConfig)
	global.GlobalConfig = &ServerConfig
}

func InitalizeLoggeer() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		//global.GlobalConfig.Service.LogPath,
		"stderr",
		"stdout",
		//构建并初始化
	}
	logger, _ := config.Build()
	zap.ReplaceGlobals(logger)
}

func InitConsul() {
	config := api.DefaultConfig()
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}

	global.ConsulClient = client

	consulRpcClient := consul.NewRegisterClient(global.GlobalConfig.Consule.Host, global.GlobalConfig.Consule.Port)
	result := consulRpcClient.FilterService(global.GlobalConfig.Consule.Name)
	SrvIp := ""
	for _, s := range result {
		SrvIp = s.Address
		break
	}
	if SrvIp == "" {
		err = consulRpcClient.RegisterConsul()
		if err != nil {
			panic(err)
			zap.S().Panic("服务注册失败")
		} else {
			zap.S().Info("服务已经注册，无需再次注册")
		}
	}
}

func MysqlInit() {
	m := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.User, m.Pwd, m.Host, m.Port, m.DbName)
	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	err = global.DB.AutoMigrate(&models.User{})
	if err != nil {
		return
	}
	zap.S().Infow("数据库创建成功", zap.Int("code", 200))
}
